package com.wcpdoc.api.controller;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.excel.EasyExcel;
import com.wcpdoc.api.entity.UserEntity;
import com.wcpdoc.base.entity.TagInfo;
import com.wcpdoc.base.service.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.wcpdoc.base.entity.Org;
import com.wcpdoc.base.entity.User;
import com.wcpdoc.core.controller.BaseController;
import com.wcpdoc.core.entity.PageIn;
import com.wcpdoc.core.entity.PageOut;
import com.wcpdoc.core.entity.PageResult;
import com.wcpdoc.core.entity.PageResultEx;
import com.wcpdoc.core.exception.MyException;
import com.wcpdoc.core.service.OnlineUserService;
import com.wcpdoc.core.util.StringUtil;
import com.wcpdoc.core.util.ValidateUtil;
import com.wcpdoc.file.service.FileService;

/**
 * 用户控制层
 * <p>
 * v1.0 zhanghc 2016-6-15下午17:24:19
 */
@Controller
@RequestMapping("/api/user")
public class ApiUserController extends BaseController {
    private static final Logger log = LoggerFactory.getLogger(ApiUserController.class);

    @Resource
    private UserService userService;
    @Resource
    private UserExService userExService;
    @Resource
    private OrgService orgService;
    @Resource
    private OnlineUserService onlineUserService;
    @Resource
    private FileService fileService;

    /**
     * 用户列表
     *
     * @return PageOut
     */
    @RequestMapping("/listpage")
    @ResponseBody
    public PageResult listpage() {
        try {
            PageIn pageIn = new PageIn(request);
            log.info("====查询用户列表");
            log.info(pageIn.toString());
            if (getCurUser().getType() == 0) {// 如果是管理员
                if (!ValidateUtil.isValid(pageIn.get("type"))) {// 默认查询考试用户
                    pageIn.addAttr("type", "1");
                } else /*if (pageIn.get("type").equals("3"))*/ {
                    pageIn.addAttr("parentId", getCurUser().getId());
                }
            } else if (getCurUser().getType() == 2) {// 如果是子管理
                if (!ValidateUtil.isValid(pageIn.get("type")) || pageIn.get("type").equals("1")) {// 默认查询考试用户
                    User user = userService.getEntity(getCurUser().getId());
                    pageIn.addAttr("ids", StringUtil.join(user.getUserIds()));
                } else /*if (pageIn.get("type").equals("3"))*/ {// 查看阅卷用户
                    pageIn.addAttr("parentId", getCurUser().getId());
                }
            } else if (getCurUser().getType() == 3) {// 阅卷用户没有角色权限

            } else if (getCurUser().getType() == 1) {// 考试用户没有角色权限

            }
            log.info(pageIn.toString());
            PageOut pageOut = userService.getListpage(pageIn);
            return PageResultEx.ok().data(pageOut);
        } catch (Exception e) {
            log.error("用户列表错误：", e);
            return PageResult.err();
        }
    }

    @RequestMapping("/exam/export")
    public void exportExcel(HttpServletResponse response) {
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        Integer AdminId = getCurUser().getId();
        List<Map<String, Object>> data = userService.getListUser(String.valueOf(AdminId));
        List<UserEntity> dataList = new ArrayList<>();
        for (Map<String, Object> map : data) {
            UserEntity dataItem = new UserEntity();
            dataItem.setName(String.valueOf(map.get("name")));
            dataItem.setLoginName(String.valueOf(map.get("loginName")));
            dataItem.setOrgName(String.valueOf(map.get("orgName")));
            dataItem.setState(String.valueOf(map.get("state")));
            dataItem.setSex(String.valueOf(map.get("sex")));

            dataItem.setLabelId(String.valueOf(map.get("labelName")));


            dataList.add(dataItem);
        }

        // 文件名
        String fileName;
        fileName = "用户数据";
        try {
            // 文件名，编码格式
            fileName = URLEncoder.encode(fileName, "UTF-8");

            // 文件格式
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");

            // 使用EasyExcel工具写excel
            EasyExcel.write(response.getOutputStream(), UserEntity.class).sheet("logs").doWrite(dataList);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 用户添加
     * <p>
     * v1.0 zhanghc 2016-6-15下午17:24:19
     *
     * @param user
     * @return PageResult
     */
    @RequestMapping("/add")
    @ResponseBody
    public PageResult add(User user) {
        try {
            log.info(user.toString());
            // 用户添加
            userService.addEx(user);
            // 密码初始化
            String initPwd = userService.pwdInit(user.getId());
            Map<String, Object> data = new HashMap<String, Object>();
            data.put("initPwd", initPwd);
            return PageResultEx.ok().data(data);
        } catch (MyException e) {
            log.error("用户添加错误：{}", e.getMessage());
            return PageResult.err().msg(e.getMessage());
        } catch (Exception e) {
            log.error("用户添加错误：", e);
            return PageResult.err();
        }
    }

    /**
     * 用户修改
     * <p>
     * v1.0 zhanghc 2016-6-15下午17:24:19
     *
     * @param user
     * @return PageResult
     */
    @RequestMapping("/edit")
    @ResponseBody
    public PageResult edit(User user) {
        try {
            // 用户修改
            User entity = userService.getEntity(user.getId());
            String oldLoginName = entity.getLoginName();
            userService.editEx(user);
            String newLoginName = entity.getLoginName();

            // 更新密码
            Map<String, Object> data = new HashMap<String, Object>();
            if (!oldLoginName.equals(newLoginName)) {
                String initPwd = userService.pwdInit(user.getId());
                data.put("initPwd", initPwd);
            }

            return PageResultEx.ok().data(data);
        } catch (MyException e) {
            log.error("用户修改错误：{}", e.getMessage());
            return PageResult.err().msg(e.getMessage());
        } catch (Exception e) {
            log.error("用户修改错误：", e);
            return PageResult.err();
        }
    }

    /**
     * 用户删除
     * <p>
     * v1.0 zhanghc 2016-6-15下午17:24:19
     *
     * @param id
     * @return PageResult
     */
    @RequestMapping("/del")
    @ResponseBody
    public PageResult del(Integer id) {
        try {

            userService.delEx(id);
            return PageResult.ok();
        } catch (MyException e) {
            log.error("用户删除错误：{}", e.getMessage());
            return PageResult.err().msg(e.getMessage());
        } catch (Exception e) {
            log.error("用户删除错误：", e);
            return PageResult.err();
        }
    }

    /**
     * 用户获取
     * <p>
     * v1.0 zhanghc 2016-6-15下午17:24:19
     *
     * @param id
     * @return PageResult
     */
    @RequestMapping("/get")
    @ResponseBody
    public PageResult get(Integer id) {
        try {
            if (!ValidateUtil.isValid(id)) {
                id = getCurUser().getId();
            }
            User user = userService.getEntity(id);
            Org org = null;
            if (user.getOrgId() != null) {
                org = orgService.getEntity(user.getOrgId());
            }

            PageResultEx pageResult = PageResultEx.ok()
                    .addAttr("id", user.getId())
                    .addAttr("name", user.getName())
                    .addAttr("sex", user.getSex())
                    .addAttr("loginName", user.getLoginName())
                    .addAttr("orgId", user.getOrgId())
                    .addAttr("orgName", org == null ? null : org.getName())
                    .addAttr("state", user.getState())
                    .addAttr("userIds", user.getUserIds())
                    .addAttr("orgIds", user.getOrgIds())
                    .addAttr("labelId", user.getLabelId())
                    .addAttr("phone",user.getPhone());
            return pageResult;
        } catch (MyException e) {
            log.error("用户获取错误：{}", e.getMessage());
            return PageResult.err().msg(e.getMessage());
        } catch (Exception e) {
            log.error("用户获取错误：", e);
            return PageResult.err();
        }
    }

    /**
     * 密码初始化
     * <p>
     * v1.0 zhanghc 2017年7月13日下午9:27:18
     *
     * @param id
     * @return PageResult
     */
    @RequestMapping("/pwdInit")
    @ResponseBody
    public PageResult pwdInit(Integer id) {
        try {
            String pwdInit = userService.pwdInit(id);
            Map<String, Object> data = new HashMap<String, Object>();
            data.put("initPwd", pwdInit);
            return PageResultEx.ok().data(data);
        } catch (MyException e) {
            log.error("密码初始化错误：{}", e.getMessage());
            return PageResult.err().msg(e.getMessage());
        } catch (Exception e) {
            log.error("密码初始化错误：", e);
            return PageResult.err();
        }
    }

    /**
     * 用户冻结
     * <p>
     * v1.0 chenyun 2022年04月21日下午3:36:55
     *
     * @return pageOut
     */
    @RequestMapping("/frozen")
    @ResponseBody
    public PageResult frozen(Integer id) {
        try {
            userService.frozen(id);
            return PageResult.ok();
        } catch (Exception e) {
            log.error("账户冻结错误：", e);
            return PageResult.err();
        }
    }

    /**
     * 退出登陆
     * <p>
     * v1.0 zhanghc 2016年8月27日上午11:36:55
     *
     * @return pageOut
     */
    @RequestMapping("/out")
    @ResponseBody
    public PageResult out(Integer id) {
        try {
            onlineUserService.out(id);
            return PageResult.ok();
        } catch (Exception e) {
            log.error("退出登陆错误：", e);
            return PageResult.err();
        }
    }

    /**
     * 用户导入
     * <p>
     * v1.0 chenyun 2021年3月4日下午5:41:02
     *
     * @return PageResult
     */
    @RequestMapping("/import")
    @ResponseBody
    public PageResult xlsImport(Integer fileId) {
        try {
            log.info("=======用户导入");
            log.info("=======用户导入" + fileId);
            userExService.xlsImport(fileId);
            return PageResultEx.ok();
        } catch (MyException e) {
            log.error("用户导入错误：{}", e.getMessage());
            return PageResult.err().msg(e.getMessage());
        } catch (Exception e) {
            log.error("用户导入错误：", e);
            return PageResult.err();
        }
    }

    /**
     * 用户模板导出
     * <p>
     * v1.0 chenyun 2021年3月4日下午5:41:02
     *
     * @return PageResult
     */
    @RequestMapping("/template")
    @ResponseBody
    public void template() {
        try {
//            fileService.exportTemplate("用户.xlsx");
            fileService.exportTemplate("用户2.xlsx");
        } catch (Exception e) {
            log.error("用户模板导出失败：", e);
        }
    }


}
